package dataBase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.NameFilter;
import tools.SQLTools;


import java.lang.reflect.Type;

public class DataSetTools {

    public DataSetTools()
    {

    }

    public static String getJson(DataSet dataSet)
    {
        NameFilter filter = new NameFilter() {

            @Override
            public String  process(Object source, String name, Object value) {

                System.out.println("----------------source=" + source);
                System.out.println("----------------name=" + name);
                System.out.println("----------------value=" + value);
                System.out.println("");
                // 属性是id并且大于等于100时进行序列化
                if ("ROWID".equals(name)) {
                    //long id = ((Long) value).longValue();
                    //return id >= 100;
                    name = ((Row)source).getValue("icode").toString();

                }
                return name;
            }
        };



        String jsonString = JSON.toJSONString(dataSet,filter);

        return jsonString;
    }

    static int rowid = 0;
    /**
     * 在jsp里使用
     * <%

     int pno=1;
     try
     {
     pno = Integer.parseInt(request.getParameter("pno"));

     }
     catch(Exception e)
     {

     }
     finally
     {
     //     pno = 1;

     }
     int numperpage = 3;

     com.base.myproject.server.tools.DataSetTool dst = new com.base.myproject.server.tools.DataSetTool();

     DataSetInfo dsi  = new  DataSetInfo();
     dsi.setTableCss("table1");
     dsi.setPagenow(pno);
     dsi.setPerpagenum(10);
     dsi.setXianshikuaishu(1);
     dsi.setQuerysql("select * from  ccode");
     // dsi.setPagesql("select * from  ccode limit "+(dsi.getPagenow()-1)*dsi.getPerpagenum()+","+dsi.getPerpagenum());

     dsi.setColumnname(new String[]{"ccode","cname"});
     dsi.setColumndisplayname(new String[]{"编码", "名称"});
     dsi.setIsneedpage(true);
     dsi.setPageurl(  request.getRequestURI());


     String sss = dst.getPagetable(dsi);
     %>
     <%=sss%>
     * @param dsinfo
     * @return
     */
    public String getPagetable(DataSetInfo dsinfo) throws Exception {
        StringBuffer sb = new StringBuffer();

        if(dsinfo.getDstotalcount()<0)
        {

//            DataSet dst = new DataSetTool().getDataSet(dsinfo.getQuerysql());
//            String querysql = "select count(*) from ("+dsinfo.getQuerysql()+" )as a";

            try {
                dsinfo.setDstotalcount(Integer.parseInt(SQLTools.getInstance().query("select count(*) from (" + dsinfo.getQuerysql() + " )as a").getValue(0, 0).toString()));
            }
            catch (Exception e)
            {
                dsinfo.setDstotalcount(0);
            }
        }


        int kuai = dsinfo.getDstotalcount()/dsinfo.getPerpagenum()+(dsinfo.getDstotalcount()%dsinfo.getPerpagenum()>0?1:0);
        if(dsinfo.getPagenow()>kuai)
            dsinfo.setPagenow(kuai);
        if(dsinfo.getPagenow()<=0)
            dsinfo.setPagenow(1);


        dsinfo.setDs( SQLTools.getInstance().query("select * from ("+dsinfo.getQuerysql()+" ) as a limit "+(dsinfo.getPagenow()-1)*dsinfo.getPerpagenum()+","+dsinfo.getPerpagenum()));

        boolean firstbingo = true; // 首次命中，设置开头table
        boolean issetfirstbingo = false;// 已经出现过首次命中需要设置结束</table>

        sb.append("<div style=\"padding:0px;margin:8px\"><table class='"
                + dsinfo.getTableCss()
                + "' "
                + (dsinfo.getTableid() == null ? "" : (" id=" + dsinfo
                .getTableid())) + ">");
        boolean b = dsinfo.getNeeddownload();
        for (int i = 0; i < dsinfo.getDs().getRowCount(); i++) {

            String downstr = "";
            if(b)
            {
                downstr = "<button onclick=\"javascript:location.href = location.href+'&ExcelDown=true'\" title=\"xls\"  style=\"height: 20px; margin: 0px; padding: 0px; float:right; right: 1em; top: 1%; z-index: 10;\">excel下载</button>\n";
            }
            if (b) {
                //加入了下载xls的按钮zgw 20140205
                sb.append("<tr><TH colspan='"
                        + (dsinfo.isNeedCheckBox()?dsinfo.getColumndisplayname().length+1:dsinfo.getColumndisplayname().length)
                        + "'>"
                        + (dsinfo.getDatasettitle() == null ? "" : dsinfo
                        .getDatasettitle()) +downstr+ "</TH>  </tr>");

                sb.append("<tr >");
                //如果需要checkbox，那么要加入空的th
                if(dsinfo.isNeedCheckBox()) {
                    sb.append("<th width=10px></th>");
                }
                for (String c : dsinfo.getColumndisplayname()) {
                    sb.append("<th>" + c + "</th>");
                }
                sb.append("</tr>");
            }

            sb.append("<tr class='truerow' id='" + (dsinfo.getMacro().get("rowid")==null?rowid++:dsinfo.getDs().getValue(i, dsinfo.getMacro().get("rowid"))) + "'>");
            //如果需要checkbox，
            if(dsinfo.isNeedCheckBox()) {
                sb.append("<td><input id=\"checkBox\" type=\"checkbox\"></td>");
            }

            for (String c : dsinfo.getColumnname()) {
                sb.append("<td>"
                        + (dsinfo.getDs().getValue(i, c) == null ? "" : dsinfo
                        .getDs().getValue(i, c)) + "</td>");
            }
            sb.append("</tr>");

            for (int j = 0; j < dsinfo.getChileDSinfo().size(); j++) {
                DataSetInfo dstemp = dsinfo.getChileDSinfo().get(j);
                DataSet ds = new DataSet();
                String[] parentstr = dstemp.getParentLinkString();
                String[] chilestr = dstemp.getChileLinkString();

                DataSetInfo dstempcopy = (DataSetInfo) dstemp.clone();
                for (int m = 0; m < dstemp.getDs().getRowCount(); m++) {

                    // 找关联的数据
                    for (int k = 0; k < parentstr.length; k++) {

                        if (dsinfo
                                .getDs()
                                .getValue(i, parentstr[k])
                                .equals(dstemp.getDs().getValue(m, chilestr[k]))) {

                            b = true;
                        } else {

                            b = false;
                            break;
                        }

                    }
                    if (b) {
                        ds.addRow(dstemp.getDs().getRow(m));
                    }

                }

                dstempcopy.setDs(ds);
                sb.append("<tr class='notruerow' id='" + rowid++
                        + "' style=\" display:none\" > <td colspan='"
                        + dsinfo.getColumndisplayname().length + "'>"
                        + getPagetable(dstempcopy) + "</td></tr>");
            }
            b = false;
        }

        if(dsinfo.isIsneedpage())
        {
//            Htmltools ht = new Htmltools();
//
//            String pagestr = ht.getPageHtml(dsinfo.getPageurl().indexOf("?")>0?dsinfo.getPageurl():dsinfo.getPageurl()+"?1=1", dsinfo.getPagenow(), dsinfo.getDstotalcount(), dsinfo.getPerpagenum(), dsinfo.getXianshikuaishu());
//            sb.append("</table>"+pagestr+"</div>");
        }
        else
        {
            sb.append("</table></div>");
        }
        return new String(sb);
    }


    public static void main(String[] argc){
        String str ="[{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"0\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"1\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"2\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"3\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"4\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"5\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"6\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"7\"},{\"sex\":\"男\",\"name\":\"名字\",\"id\":\"8\"}]";
        JSON j = JSON.parseArray(str);
        System.out.println(j);

        JSON j2 = JSON.parseObject(str, (Type) DataSet.class);
        System.out.println(j2);







    }
}
